package com.example.book3chp01sba.car.controller;

import com.example.book3chp01sba.car.dao.CarTypeDao;
import com.example.book3chp01sba.car.entity.CarType;
import com.example.book3chp01sba.car.utils.ReponseResult;
import com.example.book3chp01sba.car.utils.enums.ResultCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@CrossOrigin
@Controller
@RequestMapping("/cartype")
@Slf4j
public class CarTypeController {

    @Autowired
    CarTypeDao carTypeDao;

    @RequestMapping("/all")
    @ResponseBody
    public ReponseResult getAll(){
        log.debug("getAll...");
        return new ReponseResult(carTypeDao.getAll());
    }

    @RequestMapping("/one/{tid}")
    @ResponseBody
    public ReponseResult getOne(@PathVariable("tid") Integer tid){

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return new ReponseResult(carTypeDao.getById(tid));
    }

    @PostMapping("/add")
    @ResponseBody
    public ReponseResult add(CarType carType){
        carTypeDao.add(carType);
        return new ReponseResult(carType.getTid());
    }

    @PostMapping("/update")
    @ResponseBody
    public ReponseResult update(CarType carType){
        carTypeDao.update(carType);
        return new ReponseResult();
    }

    @DeleteMapping("/delete")
    @ResponseBody
    public ReponseResult delete(int tid){
        CarType carType = carTypeDao.getById(tid);
        carTypeDao.delete(tid);
        return new ReponseResult(carType);
    }

    @RequestMapping("/update1")
    @ResponseBody
    public Object update1(HttpServletRequest request){
        CarType carType = new CarType();
        carType.setTid(Integer.parseInt(request.getParameter("tid")));
        carType.setName(request.getParameter("name"));
        return carType;
    }

    @RequestMapping("/update2")
    @ResponseBody
    public Object update2(int tid,String name){
        CarType carType = new CarType();
        carType.setTid(tid);
        carType.setName(name);
        return carType;
    }

    @PostMapping("/update3")
    @ResponseBody
    public Object update3(CarType carType){
        return carType;
    }
}
